#include "formpayments.h"
#include "ui_formpayments.h"
#include <QDebug>
#include <QAbstractProxyModel>
#include <modelcontainer.h>

FormPayments::FormPayments(QWidget *parent) :
    QWidget(parent),
    mp_completer(NULL),
    ui(new Ui::FormPayments)
{
    ui->setupUi(this);
    mp_completer = new QCompleter(this);
    mp_qstr_model = new QStringListModel(this);
    connect(mp_completer, SIGNAL(activated(QModelIndex)), this, SLOT(completer_activated(QModelIndex)));
    connect(ui->combo_houses, SIGNAL(currentIndexChanged(int)), this, SLOT(hcombo_current_changed()));
    connect(ui->combo_apartments, SIGNAL(currentIndexChanged(int)), this, SLOT(apcombo_current_changed()));
    connect(ui->btn_check_all_spaces, SIGNAL(clicked()), this, SLOT(set_checked_all_spaces()));
    connect(ui->btn_uncheck_all_spaces, SIGNAL(clicked()), this, SLOT(set_unchecked_all_spaces()));
    connect(ui->btn_del_payment, SIGNAL(clicked()), this, SLOT(del_payment()));
    connect(ui->btn_add_payment, SIGNAL(clicked()), this, SLOT(add_payment()));
    connect(ui->ledit_ammount, SIGNAL(returnPressed()), this, SLOT(add_payment()));

    mqv_bill_index  = (quint64) 0ll;

    for(int i = 0; i< 100; i++)
    {
        ui->combo_year->addItem(QString::number(2000+i));
    }
    QDate qd = QDate::currentDate();
    ui->combo_year->setCurrentIndex(qd.year() - 2000);
    ui->combo_month->setCurrentIndex(qd.month()-1);

    connect(ui->combo_month, SIGNAL(currentIndexChanged(int)), this, SLOT(update_spaces_list()));
    connect(ui->combo_year, SIGNAL(editTextChanged(QString)), this, SLOT(update_spaces_list()));
    ui->dedit_paymentdate->setDate(QDate::currentDate());
    ui->ledit_ammount->setValidator(new QDoubleValidator(this));

    connect(ui->ledit_bill_number, SIGNAL(textEdited(QString)), this, SLOT(bill_number_edited(QString)));
    ui->tedit_lease_info->hide();
}

FormPayments::~FormPayments()
{
    delete ui;
}

void FormPayments::set_dbms(HousingDBMS *p_dbms)
{
    mp_dbms = p_dbms;
    mp_model = dynamic_cast<ModelContainer *>(mp_dbms->get_models())->get_payments_model();
}


void FormPayments::update_data()
{
    SLEE_HDB_REC_LST qhl_streets;
    mqvl_h_indices.clear();
    mqvl_s_indices.clear();
    mqvl_s_indices = mp_dbms->get_db(LAKDB_STREETS)->findDataRange(FLD_STDB_NAME,NULL, true, NULL, false, &qhl_streets);
    qhl_streets.removeFirst();
    mqvl_s_indices.removeFirst();
    QStringList qstrl;
    foreach(SLEE_HDB_REC qh_data, qhl_streets)
    {
        qstrl.append(mp_dbms->get_street_info(qh_data,true));
    }
    mp_qstr_model->setStringList(qstrl);
    mp_completer->setCaseSensitivity(Qt::CaseInsensitive);
    mp_completer->setModel(mp_qstr_model);
    ui->ledit_street->setCompleter(mp_completer);
    ui->combo_houses->clear();

    show_payments();
     connect(ui->combo_filter, SIGNAL(currentIndexChanged(int)), this, SLOT(show_payments()));
     connect(ui->combo_month, SIGNAL(currentIndexChanged(int)), this, SLOT(show_payments()));
     connect(ui->combo_year, SIGNAL(currentIndexChanged(int)), this, SLOT(show_payments()));
}


void FormPayments::completer_activated(const QModelIndex &index)
{
    QAbstractProxyModel *p_model = (QAbstractProxyModel *)mp_completer->completionModel();
    QModelIndex indx = p_model->mapToSource(index);
    mqv_current_s_index = mqvl_s_indices.at(indx.row());
    SLEE_HDB_REC_LST qhl_data;
    mqvl_h_indices = mp_dbms->get_db(LAKDB_HOUSES)->findDataEq(FLD_HSDB_STINDEX, mqv_current_s_index,&qhl_data);
    ui->combo_houses->clear();
    foreach(SLEE_HDB_REC qh_data, qhl_data)
    {
        ui->combo_houses->addItem(mp_dbms->get_house_info(qh_data));
    }
}

void FormPayments::hcombo_current_changed()
{
    ui->combo_apartments->clear();
    if(!mqvl_h_indices.size()) return;
    if(!ui->combo_houses->count()) return;
    mqv_current_h_index = mqvl_h_indices.at(ui->combo_houses->currentIndex());
    SLEE_HDB_REC_LST qhl_data;
    mqvl_ap_indices = mp_dbms->get_db(LAKDB_APARTMENTS)->findDataEq(FLD_APDB_HSINDEX, mqv_current_h_index, &qhl_data);
    foreach(SLEE_HDB_REC qh_data, qhl_data)
    {
        ui->combo_apartments->addItem(mp_dbms->get_apartment_info(qh_data,false));
    }

}

void FormPayments::apcombo_current_changed()
{

    if(!mqvl_ap_indices.size()) return;
    if(!ui->combo_apartments->count()) return;
    mqv_current_a_index = mqvl_ap_indices.at(ui->combo_apartments->currentIndex());
    update_spaces_list();
    show_payments();
}


void FormPayments::update_spaces_list()
{
    ui->list_spaces->clear();
    if(mqv_current_a_index.isNull()) return;
    SLEE_HDB_REC qh_data = mp_dbms->get_data(LAKDB_APARTMENTS, mqv_current_a_index);
    mqvh_spaces = qh_data.value(FLD_APDB_LSPSHASH).toHash();
    qDebug()<<"payments::update spaces list...ap spaces: "<<mqvh_spaces<<" hash size: "<<mqvh_spaces.size();
    QVariantHash qvh_pdates = qh_data.value(FLD_APDB_PDATEHASH).toHash();
    QDate qd;
    qd.setYMD(ui->combo_year->currentText().toInt(),ui->combo_month->currentIndex()+1, 15);
    int i = 0;
    foreach(QString qstr_id, mqvh_spaces.keys())
    {
        QString qstr;
        qstr = mqvh_spaces.value(qstr_id).toString();
        QDate pdate = qvh_pdates.value(qstr_id).toDate();
        if(pdate.isNull()) pdate.setYMD(2222,2,2);
        if(pdate < qd)
        {
            qstr+= RUSTR(" приватизированно ") ;
            qstr += pdate.toString("dd.MM.yyyy");
        }
        ui->list_spaces->addItem(RUSTR("№%1: ").arg(i+1) + qstr + RUSTR(" кв.м."));
        QListWidgetItem *p_i = ui->list_spaces->item(ui->list_spaces->count()-1);
        p_i->setCheckState(Qt::Unchecked);
        if(pdate < qd)
            p_i->setFlags(Qt::NoItemFlags);
        i++;
    }
}


void FormPayments::set_checked_all_spaces()
{
    for(int i = 0; i<ui->list_spaces->count(); i++)
    {
        QListWidgetItem *p_i = ui->list_spaces->item(i);
       if(p_i->flags() == Qt::NoItemFlags) continue;
       p_i->setCheckState(Qt::Checked);
    }
}

void FormPayments::set_unchecked_all_spaces()
{
    for(int i = 0; i<ui->list_spaces->count(); i++)
    {
       QListWidgetItem *p_i = ui->list_spaces->item(i);
       if(p_i->flags() == Qt::NoItemFlags) continue;
       p_i->setCheckState(Qt::Unchecked);
    }
}

//void FormPayments::show_current_payments()
//{
//    QDate qd;
//    qd.setYMD(ui->combo_year->currentText().toInt(),ui->combo_month->currentIndex()+1, 15);
//    ui->tv_payments->setModel(NULL);
//    mp_model->load_data(qd,mqv_current_a_index);
//    ui->tv_payments->setModel(mp_model);
//    resize_table();
//}

void FormPayments::show_payments()
{
   QVariant qv_a_index;
   QDate qd;
   switch (ui->combo_filter->currentIndex())
   {
    case 0: qv_a_index = mqv_current_a_index; qd.setYMD(ui->combo_year->currentText().toInt(),ui->combo_month->currentIndex()+1, 15);
       break;
    case 1: qv_a_index = mqv_current_a_index;
        break;
    case 2: qd.setYMD(ui->combo_year->currentText().toInt(),ui->combo_month->currentIndex()+1, 15);
       break;
   }
   ui->tv_payments->setModel(NULL);
   mp_model->load_data(qd, qv_a_index);
   ui->tv_payments->setModel(mp_model);
   resize_table();
}


//0 - apartment info
//1 - targed_date
//2 - payment date
//3 - ammount
//4 - total space
void FormPayments::resize_table()
{
    int x = ui->tv_payments->size().width();
    ui->tv_payments->setColumnWidth(0, x/10);
    ui->tv_payments->setColumnWidth(1, x/10);
    ui->tv_payments->setColumnWidth(2, x/3);
    ui->tv_payments->setColumnWidth(3, x/7);
    ui->tv_payments->setColumnWidth(4, x/7);
    ui->tv_payments->setColumnWidth(5, x/8);
    ui->tv_payments->setColumnWidth(6, x/5);
}

void FormPayments::resizeEvent(QResizeEvent *)
{
    resize_table();
}

void FormPayments::del_payment()
{
    QModelIndex c_i =  ui->tv_payments->currentIndex();
    if(!c_i.isValid())
    {
        lakhMsgE()<<RUSTR("Ошибка. Не выбран платеж.");
        return;
    }

    QVariant qv_p_i = mp_model->get_db_index(c_i);
    if(!mp_dbms->can_remove(LAKDB_PAYMENTS, qv_p_i)) return;
    SLEE_HDB_REC qh_data = mp_dbms->get_data(LAKDB_PAYMENTS, qv_p_i);
    mp_dbms->get_db(LAKDB_PAYMENTS)->removeData(qh_data, qv_p_i);
    show_payments();
    lakhMsg()<<RUSTR("Платеж удален из БД.");
}

void FormPayments::add_payment()
{
    SLEE_HDB_REC qh_data;
    if(mqv_current_a_index.isNull())
    {
        lakhMsgE()<<RUSTR("Ошибка.Не указано жилое помещение.");
        return;
    }
    qh_data[FLD_PAY_AINDEX] = mqv_current_a_index;
    if(mqv_bill_index.toULongLong() != 0ll)
    {
        SLEE_HDB_REC qh_bill = mp_dbms->get_data(LAKDB_BILLS, mqv_bill_index);
        qh_data[FLD_PAY_LINDEX] = qh_bill.value(FLD_BILL_LINDEX);
    }
    else
        qh_data[FLD_PAY_LINDEX] = (quint64) 0ll;
    qh_data[FLD_PAY_BINDEX] = mqv_bill_index;
    QDate qd;
    qd.setYMD(ui->combo_year->currentText().toInt(),ui->combo_month->currentIndex()+1, 15);
    qh_data[FLD_PAY_TARGETDATE] = qd;
    qh_data[FLD_PAY_DATE] = ui->dedit_paymentdate->date();
    if(!ui->ledit_ammount->text().size())
    {
        lakhMsgE()<<RUSTR("Ошибка.Не указана сумма платежа.");
        return;
    }
    qh_data[FLD_PAY_AMMOUNT] = ui->ledit_ammount->text().toDouble();
    QStringList qsl_sid;
    for(int i = 0; i<ui->list_spaces->count(); i++)
    {
        QListWidgetItem *p_i = ui->list_spaces->item(i);
        if(p_i->checkState() == Qt::Checked)
        {
            qsl_sid.append(mqvh_spaces.keys().at(i));
        }
    }
    if(!qsl_sid.size())
    {
        lakhMsgE()<<RUSTR("Ошибка.Не отмечены жилые площади.");
        return;
    }
    qh_data[FLD_PAY_SPSLST] = QVariant(qsl_sid);
    qDebug()<<qh_data;
    mp_dbms->db_put(LAKDB_PAYMENTS, qh_data);
    show_payments();
    lakhMsg()<<RUSTR("Платеж внесен в БД");
}


void FormPayments::bill_number_edited(QString text)
{
    QVariant qv_bill_index = QVariant(text.toULongLong());
    SLEE_HDB_REC qh_bill = mp_dbms->get_data(LAKDB_BILLS, qv_bill_index);
    ui->ledit_street->setCompleter(NULL);
    ui->combo_apartments->clear();
    ui->combo_houses->clear();
    ui->ledit_street->setReadOnly(true);
    ui->list_spaces->clear();
    ui->btn_check_all_spaces->setEnabled(false);
    ui->btn_uncheck_all_spaces->setEnabled(false);
    ui->tedit_lease_info->hide();
    mqvl_s_indices = mqvl_h_indices = mqvl_ap_indices = QVariantList();
    ui->combo_month->setEnabled(false);
    ui->combo_year->setEnabled(false);
    ui->ledit_bill_ammount->clear();
    if(qh_bill.isEmpty())
    {
        ui->ledit_street->setText(QString());
        ui->ledit_street->setCompleter(mp_completer);
        ui->ledit_street->setReadOnly(false);
        ui->btn_check_all_spaces->setEnabled(true);
        ui->btn_uncheck_all_spaces->setEnabled(true);
        ui->combo_month->setEditable(true);
        ui->combo_year->setEnabled(true);
        mqv_bill_index = QVariant((quint64)0ll);
        return;
    }
    if(qh_bill.value(FLD_BILL_LINDEX).toULongLong() != 0ll)
    {
        ui->tedit_lease_info->setPlainText(mp_dbms->get_lease_info(qh_bill.value(FLD_BILL_LINDEX)));
        ui->tedit_lease_info->show();
    }
    ui->ledit_bill_ammount->setText(qh_bill.value(FLD_BILL_AMMOUNT).toString());
    mqv_bill_index = qv_bill_index;
    mqv_current_a_index = qh_bill.value(FLD_BILL_AINDEX);
    SLEE_HDB_REC qh_ap_data = mp_dbms->get_data(LAKDB_APARTMENTS, mqv_current_a_index);
    mqv_current_h_index = qh_ap_data.value(FLD_APDB_HSINDEX);
    SLEE_HDB_REC qh_h_data = mp_dbms->get_data(LAKDB_HOUSES, mqv_current_h_index);
    mqv_current_s_index = qh_h_data.value(FLD_HSDB_STINDEX);
    SLEE_HDB_REC qh_s_data = mp_dbms->get_data(LAKDB_STREETS, mqv_current_s_index);
    ui->ledit_street->setText(mp_dbms->get_street_info(qh_s_data,true));
    ui->combo_houses->addItem(mp_dbms->get_house_info(qh_h_data));
    ui->combo_apartments->addItem(mp_dbms->get_apartment_info(qh_ap_data, false));
    QDate qd_target = qh_bill.value(FLD_BILL_TARGETDATE).toDate();
    ui->combo_month->setCurrentIndex(qd_target.month()-1);
    ui->combo_year->setCurrentIndex(qd_target.year()-2000);

    qDebug()<<"bill edit...update spaces list";
    qDebug()<<"apartment: "<<mp_dbms->get_apartment_addr(mqv_current_a_index);
    update_spaces_list();
    qDebug()<<"bill edit...update spaces list...OK....process checking items";
    QStringList qsl_bill_sids = qh_bill.value(FLD_BILL_SPSLST).toStringList();
    qDebug()<<"list items: "<<ui->list_spaces->count()<<" hash spaces: "<<mqvh_spaces;
    for(int i = 0; i < ui->list_spaces->count(); i++)
    {
        QListWidgetItem *p_i = ui->list_spaces->item(i);
        QString qstr_id  = mqvh_spaces.keys().at(i);
        if(qsl_bill_sids.contains(qstr_id)) p_i->setCheckState(Qt::Checked);
        p_i->setFlags(Qt::NoItemFlags);
    }
    qDebug()<<"bill edit...OK";

}
